package com.shangxian.giveithome.service.impl;

import com.shangxian.giveithome.code.ActivityCode;
import com.shangxian.giveithome.code.CommonCode;
import com.shangxian.giveithome.controller.ImgFeiServer;
import com.shangxian.giveithome.controller.UserFeiController;
import com.shangxian.giveithome.entity.*;
import com.shangxian.giveithome.exception.ExceptionUtils;
import com.shangxian.giveithome.mapper.ActivityMapper;
import com.shangxian.giveithome.mapper.MechanismMapper;
import com.shangxian.giveithome.result.Result;
import com.shangxian.giveithome.service.ActivityService;
import com.shangxian.giveithome.utils.DateTime;
import com.shangxian.giveithome.utils.IGenerator;
import com.shangxian.giveithome.utils.PageUtils;
import com.shangxian.giveithome.utils.RqUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.shangxian.giveithome.properties.MechanismProperties.RQUrl;
import static com.shangxian.giveithome.utils.DateTime.YMD;
import static com.shangxian.giveithome.utils.DateTime.getTime;


@Service
@Slf4j
public class ActivityServiceImpl implements ActivityService {

    @Resource
    private ActivityMapper activityMapper;

    @Autowired
    private IGenerator iGenerator;

    @Resource
    private MechanismMapper mechanismMapper;

    @Resource
    private UserFeiController userFeiController;

    @Resource
    private ImgFeiServer imgFeiServer;

    /**
     * 根据机构id查询
     * 0已结束 1 进行中 2 未开始 null 则全部
     *
     * @param pageable
     * @return
     */
    @Override
    public PageableDetails queryByActivityId(ActivityScreen activityScreen, Pageable pageable) {
        //当前页
        Integer pageNum = pageable.getPageNumber();
        //每页条数
        Integer pages = pageable.getPageSize();
        Integer offSet = Math.toIntExact(activityScreen.getOffSet());
        Integer offSet1 = Math.toIntExact(activityScreen.getOffSet1());
        Long id = activityScreen.getId();
        Integer sta = activityScreen.getStatus();
        if (sta == null) {
            sta = 4;
        }
        List<ActivityStatus> activityStatuses = null;
        //总条数
        int total = 0;
        total = activityMapper.queryCount(sta, id);
        if (total == 0) {
            ExceptionUtils.error(CommonCode.DATA_ERROR);
        }
        //总页数
        int totalPages = PageUtils.returnPages(total, pages);
        //无条件查询
        if (sta == 4) {
            activityStatuses = activityMapper.queryActivityIng(id, pageNum, pages);
            if (activityStatuses.size() == pages) {
                return new PageableDetails<>(pageNum, pages, total, totalPages, activityStatuses);
            }
            int pageNums = 0;
            int pagesize = 0;
            if (activityStatuses.size() != 0) {
                offSet = pages - activityStatuses.size();//7
                pagesize = offSet;
            } else {
                pagesize = pages;
                pageNums = offSet;
            }
            List<ActivityStatus> activityStatusesEnd = activityMapper.queryActivityEnd(id, pageNums, pagesize);
            activityStatuses.addAll(activityStatusesEnd);
            if (activityStatuses.size() == pagesize) {
                offSet = offSet + pagesize;
                return new PageableDetails<>(pageNum, pagesize, total, totalPages, offSet, activityStatuses);
            }   //0 10 10 0   10 10 4 6 0
            offSet = activityStatusesEnd.size() + pageNums;
            pageNums = 0;
            if (activityStatusesEnd.size() != 0) {
                offSet1 = pagesize - activityStatusesEnd.size();//7
                pagesize = offSet1;
            } else {
                pagesize = pages;
                pageNums = offSet1;
            }
            List<ActivityStatus> activityStatusesNot = activityMapper.queryActivityNot(id, pageNums, pagesize);
            if (activityStatusesEnd.size() != pagesize) {   //0 10 10 0   10 10 4 6 0
                offSet1 = activityStatusesNot.size() + pageNums;
            } else {
                offSet1 = offSet1 + pagesize;
            }
            activityStatuses.addAll(activityStatusesNot);
            if (CollectionUtils.isEmpty(activityStatuses)) {
                ExceptionUtils.error(CommonCode.DATA_ERROR);
            }
            return new PageableDetails<>(pageNum, pagesize, total, totalPages, offSet, offSet1, activityStatuses);
        }
        //有条件查询
        switch (sta) {
            case 0:
                activityStatuses = activityMapper.queryActivityEnd(id, pageNum * pages, pages);
                break;
            case 1:
                activityStatuses = activityMapper.queryActivityIng(id, pageNum * pages, pages);
                break;
            case 2:
                activityStatuses = activityMapper.queryActivityNot(id, pageNum * pages, pages);
                break;
        }
        return new PageableDetails<>(pageNum, pages, total, totalPages, offSet, activityStatuses);
    }

    /**
     * 根据活动id查询活动详情
     *
     * @param id
     * @return
     */
    @Override
    public ActivityDetails queryByActivity(Long id) {
        Activity activity = activityMapper.queryActivityDetails(id);
        if (activity == null) {
            ExceptionUtils.error(CommonCode.DATA_ERRORS);
        }
        ActivityDetails convert = iGenerator.convert(activity, ActivityDetails.class);
        Mechanism mechanism = mechanismMapper.queryByActivityMechanism(activity.getMechanismId());
        if (mechanism == null) {
            ExceptionUtils.error(CommonCode.DATA_ERRORS);
        }
        convert.setMe_name(mechanism.getName());
        convert.setPicture(mechanism.getPicture());
        return convert;
    }

    @Override
    public ActivityDetails queryByActivityMechanism(Long id) {
        Activity activity = activityMapper.queryActivityMechanismDetails(id);
        if (activity == null) {
            ExceptionUtils.error(CommonCode.DATA_ERRORS);
        }
        return iGenerator.convert(activity, ActivityDetails.class);
    }

    @Override
    public Result queryActivityMail(Long id, Pageable pageable) {
        //当前页
        Integer pageNum = pageable.getPageNumber();
        //每页条数
        Integer pages = pageable.getPageSize();
        Integer total = activityMapper.countActivityUserMe(id);
        if (total == 0) {
            ExceptionUtils.error(CommonCode.DATA_ERROR);
        }
        List<ActiveRelationship> activeRelationships = activityMapper.queryActivityUserByMe(id, pageNum * pages, pages);
        List<Long> usIs = activeRelationships.stream().map(ActiveRelationship::getUsId).collect(Collectors.toList());
        List<UserSimple> userSimples = userFeiController.queryById(usIs);
        List<ActivityUsers> activityUsers = new ArrayList<>();
        activeRelationships.forEach(activeRelationship -> {
            ActivityUsers activityUsers1 = new ActivityUsers();
            userSimples.forEach(userSimple -> {
                if (activeRelationship.getUsId().equals(userSimple.getId())) {
                    activityUsers1.setUserSimple(userSimple);
                    activityUsers1.setSign(activeRelationship.getSign());
                }
            });
            activityUsers.add(activityUsers1);
        });
        if (CollectionUtils.isEmpty(activityUsers)) {
            ExceptionUtils.error(CommonCode.DATA_ERRORS);
        }
        Integer status0 = activityMapper.countActivityStutus0(id);
        ActivityUsersMail activityUsersMail = new ActivityUsersMail();
        activityUsersMail.setActivityUsers(activityUsers);
        activityUsersMail.setStatus0(status0);
        int totalPages = 0;
        if (total % pages != 0) {
            totalPages += 1;
        }
        return Result.success(new PageableDetails<>(pageNum, pages, total, totalPages, activityUsersMail));
    }

    @Override
    public List<ActivityStatus> queryByActivityIng(Long aLong, Integer n) {
        return activityMapper.queryActivityIng(aLong, 0, n);
    }

    /**
     * 创建活动
     *
     * @param activityInfo
     */
    @Override
    @Transactional
    public void create(ActivityInfo activityInfo) {
        activityMapper.createActivity(activityInfo);
        mechanismMapper.updateMechanismData(activityInfo.getMechanismId());
        //创建活动二维码
        createRq(activityInfo.getTempId(), "活动");
    }

    /**
     * 删除活动
     *
     * @param id
     * @param aLong
     */
    @Override
    @Transactional
    public void delete(Long id, Long aLong) {
        Integer row = activityMapper.deleteActivityExistence(id, aLong);
        if (row == 0) {
            ExceptionUtils.error(CommonCode.DATA_ERRORS);
        }
        activityMapper.delete(id);
        activityMapper.deleteActivityData(id);
        mechanismMapper.updateMechanismDataD(aLong);
        Integer st = imgFeiServer.deleteRqCode(id);
        if (st == 0) {
            ExceptionUtils.error(ActivityCode.DELETE_ERROR);
        }
    }

    /**
     * 修改活动信息
     *
     * @param activityUpdate
     */
    @Override
    @Transactional
    public void update(ActivityUpdate activityUpdate) {
        Integer row = activityMapper.queryActivityExistence(activityUpdate);
        if (row == 0) {
            ExceptionUtils.error(CommonCode.DATA_ERRORS);
        }
        activityMapper.update(activityUpdate);
        activityMapper.update_re(activityUpdate);

    }

    /**
     * 报名
     *
     * @param id
     * @param id1
     */
    @Override
    @Transactional
    public void singActivityUser(Long id, Long id1) {
        Activity activity = activityMapper.queryActivityDetails(id);
        if (activity == null) {
            ExceptionUtils.error(CommonCode.DATA_ERRORS);
        }
        activityMapper.save(activity, id1);

    }

    /**
     * 创建活动二维码
     *
     * @param id
     * @return
     */
    @Transactional
    public void createRq(Long id, String text) {
        RqCode rqCode = imgFeiServer.queryRqCode(id);
        if (rqCode.getId() == null) {
            rqCode = new RqCode();
            rqCode.setAcId(id);
            //生成二维码
            try {
                String url = RQUrl + id + ".jpg";
                rqCode.setPath(url);
                RqUtils.encode(text, null, url, true);
            } catch (Exception e) {
                log.error("生成二维码失败");
                e.printStackTrace();
            }
            imgFeiServer.saveRqCode(rqCode);
        }else{
            ExceptionUtils.error(CommonCode.DATA_ERRORS);
        }
    }

    /**
     * 查看二维码
     *
     * @param acId
     * @return
     */
    @Override
    public RqCode queryRq(Long acId) {
        Long aLong = activityMapper.queryActivityGoIng(acId);
        if (aLong == null){
            ExceptionUtils.error(ActivityCode.ACTIVITY_ERROR);
        }
        RqCode rqCode = imgFeiServer.queryRqCode(acId);
        if (rqCode == null) {
            ExceptionUtils.error(CommonCode.DATA_ERRORS);
        }
        return rqCode;
    }

    /**
     * 签到
     * @param ac_id
     * @param me_id
     * @param id
     */
    @Override
    @Transactional
    public void SignActivity(Long ac_id, Long me_id, Long id) {
        Long ing = activityMapper.queryActivityGoIng(ac_id);
        if (ing==null){
            ExceptionUtils.error(ActivityCode.ACTIVITY_ERROR);
        }
        if(!ing.equals(me_id)){
            ExceptionUtils.error(CommonCode.DATA_ERRORS);
        }
        Date date=new Date();
        date=getTime(YMD);
        activityMapper.SignActivity(ac_id,id,date);
        Activity activityInfo = activityMapper.queryActivityDetails(ac_id);
        // 更新志愿参与时长
        PutUserFei putUserFei =  new PutUserFei();
        putUserFei.setId(id);
        putUserFei.setVolunteerTime(DateTime.getDistanceTime2(activityInfo.getGoTime(), activityInfo.getEndTime()));
        userFeiController.PutUserVolunteerTime(putUserFei);
    }
}
